<template>
  <div class="pagination">
    <button
      :disabled="currentPageNo === 1"
      @click="$emit('changePageNo', currentPageNo - 1)"
    >
      上一页
    </button>
    <button v-if="startEnd.start > 1" @click="$emit('changePageNo', 1)">
      1
    </button>
    <button v-if="startEnd.start > 2">···</button>
    <template v-for="page in startEnd.end">
      <button
        :key="page"
        @click="$emit('changePageNo', page)"
        :class="{ active: currentPageNo === page }"
        v-if="page >= startEnd.start"
      >
        {{ page }}
      </button>
    </template>
    <button v-if="startEnd.end < totalPageNo - 1">···</button>
    <button
      v-if="startEnd.end < totalPageNo"
      @click="$emit('changePageNo', totalPageNo)"
    >
      {{ totalPageNo }}
    </button>
    <button
      :disabled="currentPageNo === totalPageNo"
      @click="$emit('changePageNo', currentPageNo + 1)"
    >
      下一页
    </button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: {
    currentPageNo: Number, //第二种
    total: {
      //第三种
      type: Number,
      default: 0,
    },
    pageSize: {
      type: Number,
      default: 5,
    },
    pagerCount: {
      type: Number,
      required: true,
    },
  },
  computed: {
    // 计算总页码
    totalPageNo() {
      return Math.ceil(this.total / this.pageSize);
    },

    // 计算连续页的起始位置和结束位置
    startEnd() {
      let { currentPageNo, pagerCount, totalPageNo } = this;
      // var start = 0,end = 0   ====>  var start = 0  var end = 0
      // var start = end = 0     ====>  var start = 0  end = 0
      let start = 0;
      let end = 0;
      if (pagerCount >= totalPageNo) {
        start = 1;
        end = totalPageNo;
      } else {
        start = currentPageNo - Math.floor(pagerCount / 2);
        end = currentPageNo + Math.floor(pagerCount / 2); 
        //修正左边的
        if (start < 1) {
          start = 1;
          end = pagerCount;
        }
        //修正右边的
        if (end > totalPageNo) {
          end = totalPageNo;
          start = totalPageNo - pagerCount + 1;
        }
      }
      return { start, end };
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  display: flex;
  justify-content: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
